﻿using DesignPattern.Models;
using DesignPattern.Services;
using CommunityToolkit.Mvvm.ComponentModel;
using Wpf.Ui;
using Wpf.Ui.Abstractions.Controls;
using Wpf.Ui.Controls;

namespace DesignPattern.ViewModels.Pages
{
    public partial class DesignPatternViewModel : ObservableObject, INavigationAware
    {
        private readonly DesignPatternService _designPatternService;
        private readonly INavigationService _navigationService;
        private readonly ISnackbarService _snackbarService;
        private bool _isInitialized = false;

        [ObservableProperty] private DesignPatternModel? _currentPattern;

        public DesignPatternViewModel(DesignPatternService designPatternService,
            INavigationService navigationService, ISnackbarService snackbarService)
        {
            _designPatternService = designPatternService;
            _navigationService = navigationService;
            _snackbarService = snackbarService;
        }

        // 导航到组件后触发的事件
        //WPF-UI中Navigate方法的第二个参数是DataContext，自动设置为目标页面的DataContext
        //因此导航是无法传参的，我们只能借助消息机制来传参
        //或者借助与额外的单例参数服务，导航前设置为某个值，导航后去取出这个值。
        public Task OnNavigatedToAsync()
        {
            if (!_isInitialized)
                InitializeViewModel();
            ShowSnackbarMessage();
            return Task.CompletedTask;
        }

        public Task OnNavigatedFromAsync() => Task.CompletedTask;

        private void InitializeViewModel()
        {
            // 加载默认的创建型设计模式（保证出错了页面也能有数据）
            var defaultPattern = _designPatternService.GetPatternsByType(PatternType.Creational).FirstOrDefault();
            if (defaultPattern != null)
            {
                CurrentPattern = defaultPattern;
            }

            _isInitialized = true;
        }
        // 加载指定名称的设计模式
        public void LoadPattern(string patternName)
        {
            // 获取并设置设计模式
            var pattern = _designPatternService.GetPatternByName(patternName);
            if (pattern != null)
            {
                // 设置CurrentPattern
                CurrentPattern = pattern;
            }
        }
        // 临时消息通知
        private void ShowSnackbarMessage()
        {
            // _snackbarService.Show();
            _snackbarService.Show("导航", "服务初始化成功",
                ControlAppearance.Secondary, new SymbolIcon(SymbolRegular.Fluent24, 18D), TimeSpan.FromSeconds(2));
        }
    }
}